using System;

namespace Test.ConsoleProgram.Algorithm.Solution
{
    [TestDescription("算法: 0111. 二叉树的最小深度")]
    public class No0111_MinDepth : AbsBaseTestItem
    {
        /*
        给定一个二叉树，找出其最小深度。
        最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
        说明: 叶子节点是指没有子节点的节点。
        */

        public class TreeNode
        {
            public int val;
            public TreeNode left;
            public TreeNode right;
            public TreeNode(int x) { val = x; }
        }

        public override void OnTest()
        {
            Assert.TestExe(MinDepth, new TreeNode(3)
            {
                left = new TreeNode(9),
                right = new TreeNode(20)
                {
                    left = new TreeNode(15),
                    right = new TreeNode(7)
                },
            }, 2);
            Assert.TestExe(MinDepth, new TreeNode(1)
            {
                left = new TreeNode(2),
            }, 2);
        }

        public int MinDepth(TreeNode root)
        {
            if (root == null)
                return 0;
            if (root.left == null && root.right == null)
                return 1;

            int min = int.MaxValue;
            if (root.left != null)
                min = Math.Min(MinDepth(root.left), min);
            if (root.right != null)
                min = Math.Min(MinDepth(root.right), min);

            return min += 1;
        }
    }
}
